<script setup>

import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import axios from "axios";
import { ElMessage } from "element-plus";

const props = defineProps({
  data: Object
});
const timeRange = ref('week');
const chartRef = ref(null);
const rankingList = ref([]);
let chartInstance = null;
const initChart = () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);
  const option = {
    title: {
      text: '各年龄段走路分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['19~25岁', '26~40岁', '41~60岁', '61岁及以上', '18岁以下']
    },
    series: [
      {
        name: '年龄分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: calculateAgeDistribution()
      }
    ]
  };
  chartInstance.setOption(option);
};

const calculateAgeDistribution = () => {
  const ageGroups = {
    '19~25岁': 0,
    '26~40岁': 0,
    '41~60岁': 0,
    '61岁及以上': 0,
    '18岁以下': 0
  };

  rankingList.value.forEach(item => {
    const age = item.bodyAge;
    if (age <= 18) {
      ageGroups['18岁以下'] += 1;
    } else if (age <= 25) {
      ageGroups['19~25岁'] += 1;
    } else if (age <= 40) {
      ageGroups['26~40岁'] += 1;
    } else if (age <= 60) {
      ageGroups['41~60岁'] += 1;
    } else {
      ageGroups['61岁及以上'] += 1;
    }
  });
  const total = Object.values(ageGroups).reduce((sum, count) => sum + count, 0);
  return Object.entries(ageGroups).map(([key, count]) => ({
    value: (count / total) * 10,
    name: key
  }));
};

const fetchData = () => {
  axios.get(`/health/getHealth/1/1/10`).then((response) => {
    console.log(response.data);
    rankingList.value = response.data.data.sort((a, b) => b.steps - a.steps); // 按 steps 降序排序
    initChart(); // 重新初始化图表
  });
};

onMounted(() => {
  initChart();
  fetchData();
});

watch(() => props.data, (newData) => {
  if (newData && chartInstance) {
    // 更新图表数据
    chartInstance.setOption({
      series: [{
        data: calculateAgeDistribution()
      }]
    });
  }
}, { deep: true });
</script>

<template>
  <div class="steps-trend-container">
    <div class="filter-section">
      <el-radio-group v-model="timeRange" size="small" @change="fetchData">
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="year">本年</el-radio-button>
      </el-radio-group>
    </div>
    <div class="chart-container">
      <div ref="chartRef" style="width: 100%; height: 300px;"></div>
    </div>
    <div class="ranking-container">
      <div class="ranking-title">走势排名</div>
      <div class="ranking-list">
        <div v-for="(item, index) in rankingList" :key="index" class="ranking-item">
          <span class="ranking-name">{{ item.userNickname }}</span>
          <span class="ranking-steps">{{ item.steps }}步</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.steps-trend-container {
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-section {
  margin-bottom: 20px;
  text-align: right;
}

.chart-container {
  margin-top: 20px;
}

.ranking-container {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.ranking-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.ranking-list {
  max-height: 300px;
  overflow-y: auto;
}

.ranking-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.ranking-name {
  color: #666;
}

.ranking-steps {
  color: #409EFF;
  font-weight: bold;
}
</style>